from flask import current_app, jsonify
from flask import render_template
from flask import request
from flask import session
from flask import g
from info import constants
from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_blu
from info.utils.common import user_login_data

@index_blu.route("/")
@user_login_data
def index():
    """
       显示首页
       1. 如果用户已经登录，将当前登录用户的数据传到模板中，供模板显示
       :return:
       """

    # # 取到用户id
    # user_id = session.get("user_id", None)
    # user = None
    # if user_id:
    #     # 查询用户
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user
    # 右侧新闻排行逻辑
    new_list = []
    # 取出排行数据
    try:
        new_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    # 定义一个空列表
    new_list_li = []
    for news in new_list:
        new_list_li.append(news.to_basic_dict())

    # 查询分类数据，通过模板的形式渲染出来
    categories = Category.query.all()

    category_li = []

    for category in categories:
        category_li.append(category.to_dict())
    data = {
        "user": user.to_dict() if user else None,
        "news_dict_li": new_list_li,
        "category_li": category_li
    }

    return render_template('news/index.html', data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


@index_blu.route('/news_list')
def news_list():
    """
    获取首页新闻数据
    :return:
    """
    # 获取参数
    cid = request.args.get('cid', "1")
    page = request.args.get('page', "1")
    per_page = request.args.get('per_page', "10")
    print(cid, page, per_page)
    # 效验参数
    try:
        page = int(page)
        cid = int(cid)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
        # 查询参数
        # 查询的不是最新的数据
    filters = [News.status == 0]
    if cid != 1:
        filters.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')
    # 取到当前页的数据
    news_model_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page
    # 创建一个新列表保存数据
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())
    # 数据
    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_dict_li": news_dict_li
    }
    return jsonify(errno=RET.OK, errmsg='查询成功', data=data)